package com.interview.javabasic.DataStructrue;/*
@李子宁
Happy,happy everyday!
冲鸭！
*/

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class HuffmanTree {
    public static void main(String[] args) {
        int arr[] = {13,7,8,3,29,6,1};
        Node node = createHuffmanTree(arr);
        preOrder(node);

        //测试

    }

    public static void preOrder(Node root){
        if (root!=null){
            root.preOrder();
        }else{
            System.out.println("空树");
        }
    }
    //创建赫夫曼树，返回的是赫夫曼树的根节点
    public static Node createHuffmanTree(int arr[]){
        /*
        * 1.遍历arr
        * 2.将arr的每一个元素构建成一个Node
        * 3、将Node放入list中
        *
        * */
        List<Node> nodes = new ArrayList<>();
        for (int i : arr) {
            nodes.add(new Node(i));
        }

        while (nodes.size()>1){
            Collections.sort(nodes);
            System.out.println("nodes= "+nodes);

            //取出根节点权值最小的二叉树
            Node left = nodes.get(0);
            Node right = nodes.get(1);
            Node root = new Node(left.value+right.value);
            root.left = left;
            root.right = right;
            //合成的节点进行删除，将得到的和加入到节点中
            nodes.remove(right);
            nodes.remove(left);
            nodes.add(root);
        }
        return nodes.get(0);
    }
}





//创建节点类,实现接口方便排序
class Node implements Comparable<Node>{
    int value;
    Node left;
    Node right;

    public Node(int value){
        this.value = value;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }
    @Override
    public int compareTo(Node o){
        //从小到大排序
        return (this.value - o.value);
    }

    //前序遍历
    public void preOrder(){
        System.out.println(this);
        if (this.left!=null){
            this.left.preOrder();
        }
        if (this.right!=null){
            this.right.preOrder();
        }
    }
}
